<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>计时器</title>
</head>
<body>
    <div id="app">
        <h1 id="nowTime">00:00</h1>
        <button id="settlement" onclick="settlement()">重置</button>
        <br>
        <br>
        <t id="historyTime"></t>
    </div>
</body>
</html>

<style>
    #app{
        text-align: center;
        zoom:2;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;
    }
</style>
<script>
    var refreshTime = 30;
    var lastTime = new Date();
    var lastText = "";
    var historyTimes = [];  // {start:0, end:0, duration:0}
    var nowTimeByH1 = document.querySelector("#nowTime");
    var historyTimeByDiyT = document.querySelector("#historyTime");

    function timeToString(d){
        return d.toLocaleString();
    }
    function subLocaleString(s){
        // return s.substring(13);
        return s.substring(11)
    }
    function settlement(){
        let nowTime = new Date();
        historyTimes.push({
            start: timeToString(lastTime),
            end: timeToString(nowTime),
            duration: nowTime-lastTime
        });
        // 刷新历史
        refreshHistoryTimes()
        return (lastTime = nowTime);
    }
    function getHistoryTimesString(){
        // 几点几分到几点几分
        let reText = [];
        historyTimes.forEach(t=>{
            let text= "";
            text += subLocaleString(t.start);
            text += " - ";
            text += subLocaleString(t.end);
            text += " ";
            text += new Date(t.duration - 1000*60*60*8).toTimeString().substring(0,8);
            text += ":" + t.duration%1000;

            reText.push(text);
        });
        return reText.join("<br>");
    }
    function refreshHistoryTimes(){
        historyTimeByDiyT.innerHTML = getHistoryTimesString();
    }

    setInterval(()=>{
        // 显示当前持续时间
        let text = new Date(new Date()-lastTime - 1000*60*60*8)
                                .toTimeString().substring(0,8);
        if(lastText!=text) {
            nowTimeByH1.innerText = text;
            lastText = text;
        }
    }, refreshTime);
</script>